package com.ldc.composetest.viewmodel

import android.annotation.SuppressLint
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.ldc.commonlibs.http.RetrofitClientBase
import com.ldc.composelibs.ViewModelCompose
import com.ldc.composetest.model.ArticleModel
import com.ldc.composetest.server.ComposeServer
import kotlinx.coroutines.launch

class ComposeViewModel : ViewModelCompose() {
    private val apiServer by lazy {
        RetrofitClientBase.getInstance().createServer(ComposeServer::class.java)
    }
    private var _showLoading = mutableStateOf<Boolean>(false)
    val showLoading: State<Boolean> = _showLoading

    @SuppressLint("MutableCollectionMutableState")
    private val _articleModel = mutableStateOf(mutableListOf<ArticleModel>())
    val articleModel: State<MutableList<ArticleModel>> = _articleModel


    fun getArticleList(page: Int = 0) {
        viewModelScope.launch {
            _showLoading.value = true
            val data = apiCall { apiServer.getArticleList(page) }
            if (data.isSuccess()) {
                if (1 == page) {
                    _articleModel.value = data.data!!.datas
                } else {
                    _articleModel.value.addAll(data.data!!.datas)
                }
            }
            _showLoading.value = false
        }
    }

}